package leetcode.dfs;

import java.util.LinkedList;
import java.util.Queue;

//994. 腐烂的橘子
public class OrangesRotting {

    public static void main(String[] args) {
        int[][] data = {{2, 1, 1}, {1, 1, 0}, {0, 1, 1}};

        System.out.println(orangesRotting(data));
    }

    //BFS
    public static int orangesRotting(int[][] grid) {
        int count = 0;
        int[] dx = new int[]{-1, 1, 0, 0};
        int[] dy = new int[]{0, 0, -1, 1};
        int time = 0;
        Queue<int[]> queue = new LinkedList<>();
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 2) {
                    queue.add(new int[]{i, j});
                } else if (grid[i][j] == 1) {
                    count++; //记录新鲜橘子的数量
                }
            }
        }
        while (!queue.isEmpty() && count > 0) {
            time++;
            int size = queue.size();
            for (int n = 0; n < size; n++) {
                int[] point = queue.poll();
                for (int i = 0; i < 4; i++) {

                    int mx = point[0] + dx[i];
                    int my = point[1] + dy[i];
                    if (mx >= 0 && mx < grid.length && my >= 0 && my < grid[0].length && grid[mx][my] == 1) {
                        grid[mx][my] = 2;
                        count--;
                        queue.add(new int[]{mx, my});
                    }

                }
            }


        }
        return count > 0 ? -1 : time;
    }

}

